package com.vinfai.thread.atomic;

import java.util.concurrent.atomic.AtomicInteger;

import org.junit.Assert;
import org.junit.Test;
import static org.junit.Assert.*;

public class AtomicIntegerTest {
	
	public static void main(String[] args){
		
	}
	@Test
	public void testAll() throws InterruptedException {
		final AtomicInteger val = new AtomicInteger(10);
		Assert.assertEquals(val.get(), 10);
		assertEquals(val.compareAndSet(10, 11), true);//expect=10?11:10.
		assertEquals(val.incrementAndGet(), 12);//++i;
		assertEquals(val.getAndAdd(3), 12); // first get. end +3. 返回以前的值
		assertEquals(val.addAndGet(3), 18);
		
		final AtomicInteger num = new AtomicInteger(10);
		//测试atomic 操作
		int size = 12;
		Thread[] ts  = new Thread[size];
		for(int i=0;i<size-2;i++){
			ts[i] = new Thread(){
				public void run() {
					//System.out.println(Thread.currentThread().getName()+" val is :"+num.incrementAndGet());
					num.incrementAndGet();
				}
			};
		}
		ts[10] = new Thread(){
			public void run(){
				num.decrementAndGet();
			}
		};
		ts[11] = new Thread(){
			public void run(){
				num.decrementAndGet();
			}
		};
		for(Thread t : ts){
			t.start();
		}
		
		for(Thread t : ts){
			t.join();
		}
		
		assertEquals(num.get(), 18);
	}
}
